package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加菜品
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> get(Integer page,Integer pageSize,String name){
        //分页查询Dish
        Page<Dish> pageInfo = new Page<>(page,pageSize);

        //条件查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //执行查询语句
        dishService.page(pageInfo,queryWrapper);

        //封装数据
        Page<DishDto> dtoPage = new Page<>();
        //total数据封装至dtoPage
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        //records数据封装至dtoPage
        List<Dish> records = pageInfo.getRecords();
        //通过stream流的方式操作records,然后将改变后的records赋值给新的Page对象
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //赋值
        dtoPage.setRecords(dishDtos);
        return R.success(dtoPage);
    }

    /**
     * 修改数据回显
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id){
        log.info(id.toString());
        DishDto dishDto = dishService.getWithFlavorById(id);
        return R.success(dishDto);
    }

    /**
     * 根据id删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(Long[] ids){
        log.info(ids.toString());
        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 查询菜品下拉列表
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info("dish={}",dish);
        //获取redis中缓存的dishDto数据
        List<DishDto> dishDtos =null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1

        //先从redis中获取数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断,如果获取的数据不为null,则直接返回,不走数据库
        if (dishDtos!=null){
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //条件查询
        queryWrapper.eq(Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        //条件排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        //要返回dishDto里的数据,所以要给其数据进行填充
        dishDtos = list.stream().map(dish1 -> {
            DishDto dishDto = new DishDto();
            //先给dishDto中继承的dish赋值
            BeanUtils.copyProperties(dish1,dishDto);

            Long categoryId = dish1.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //先填充口味列表信息,根据dish表的id,查询dish_flavor表中的数据,dish.id=dish_flavor.dish_id
            LambdaQueryWrapper<DishFlavor> dfQueryWrapper = new LambdaQueryWrapper<>();
            dfQueryWrapper.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dfQueryWrapper);
            //再给dishDto中的dishFlavors赋值
            dishDto.setFlavors(dishFlavors);
            return dishDto;

        }).collect(Collectors.toList());

        //走到这,说明redis中没有数据,则在第一次访问的时候,对数据进行缓存
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("dishDto={}",dishDto);
        dishService.updateWithFlavor(dishDto);
        //当后台对菜品数据进行更新时,需要删除redis中该菜品数据相关的redis
        //1.删除全部菜品redis数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        //2.精确删除对应菜品redis数据
//        String key = "dish_" + dishDto.getCategoryId() + "_1";
//        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        log.info("status:{}",status);
        log.info("ids:{}",ids);
        //如果status为1则进行批量启售操作
        Dish dish = new Dish();
        dish.setStatus(status);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        dishService.update(dish,queryWrapper);
        return R.success("批量修改成功");
    }
}
